package org.example.myleet.p457;

public class Solution {
    public boolean circularArrayLoop(int[] nums) {
        if (nums.length < 2) {
            return false;
        }
        for (int i = 0; i < nums.length; ++i) {
            if (isCycle(nums, i, getNext(nums, i), new boolean[nums.length])) {
                return true;
            }
        }
        return false;
    }

    private boolean isCycle(int[] nums, int startIdx, int curIdx, boolean[] visited) {
        if ((nums[startIdx] > 0 && nums[curIdx] < 0) || (nums[startIdx] < 0 && nums[curIdx] > 0)) {
            return false;
        }
        int nextId = getNext(nums, curIdx);
        if (nextId == curIdx) {
            return false;
        }
        if (startIdx == curIdx) {
            return true;
        }
        if (visited[nextId]) {
            return true;
        }
        visited[curIdx] = true;
        return isCycle(nums, startIdx, nextId, visited);
    }

    private int getNext(int[] nums, int curIdx) {
        int nextId = curIdx + nums[curIdx];
        if (nextId > nums.length - 1) {
            nextId = nextId % nums.length;
        }
        if (nextId < 0) {
            nextId = nums.length - ((-nextId) % nums.length);
        }
        return nextId;
    }
}
